/*
 * Copyright 2010-2013 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package commons.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Susanta Tewari
 * @version version
 * @history Created on 12/12/13.
 * @since since
 */
public class XMLUtil {

    public static Element getRootElement(final File dataFile, boolean checkSchema)
            throws Exception {

        final SAXReader reader = new SAXReader();
        Document document      = null;

        try {

            if (checkSchema) {

                reader.setValidation(true);
                reader.setFeature("http://xml.org/sax/features/validation", true);
                reader.setFeature("http://apache.org/xml/features/validation/schema", true);
                reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking",
                                  true);
                reader.setFeature("http://apache.org/xml/features/continue-after-fatal-error",
                                  false);
            }


            // 2.2 check the schema and read the file
            document = reader.read(dataFile);


            // wraps DocumentException (from reader.read) and SAXException (from reader.setFeature)

        } catch (SAXException | DocumentException ex) {
            throw new java.security.ProviderException(ex);
        }

        if (document == null) {

            throw new java.security.ProviderException("Error in parsing file "
                    + dataFile.getAbsolutePath());
        }

        return document.getRootElement();
    }

    /**
     * This method is thread safe.
     * @param document xml document to be written
     * @param filePath file to write to
     * @throws IOException when in error
     */
    public static void write(Document document, String filePath) throws IOException {

        final OutputFormat fmt = OutputFormat.createPrettyPrint();
        final XMLWriter writer = new XMLWriter(new PrintWriter(new File(filePath)), fmt);

        synchronized (writer) {

            writer.write(document);
            writer.println();    // line break; XMLWriter does n`t end w/ one
            writer.flush();
        }
    }

    private XMLUtil() {}
}
